package cn.texous.demo.demofileupload.controller;

import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * insert description here.
 *
 * @author Showa.L
 * @since 2019/10/21 17:01
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 导入CVS
     *
     * @param file 文件
     * @return re
     * @throws IOException e
     */
    @PostMapping("/uploadCSV")
    public String uploadCSV(MultipartFile file) throws IOException {
        //##CODE_START

        CsvParserSettings settings = new CsvParserSettings();
        //the file used in the example uses '\n' as the line separator sequence.
        //the line separator sequence is defined here to ensure systems such as MacOS and Windows
        //are able to process this file correctly (MacOS uses '\r'; and Windows uses '\r\n').
        settings.getFormat().setLineSeparator("\r\n");
        // creates a CSV parser  如果CSV经过Excel打开后文本格式发生改变，导入进来的是乱码
        CsvParser parser = new CsvParser(settings);

        // parses all rows in one go.
        List<String[]> allRows = parser.parseAll(file.getInputStream(), 100000);

        System.out.println(allRows);

        // 解析第一行为头部
        String[] header = allRows.remove(0);

        return "true";
    }

}
